<template>
  <div v-if="visible" class="dialog-overlay" @click="handleOverlayClick">
    <div class="dialog-content" @click.stop>
      <div class="dialog-header">
        <h3>{{ isEdit ? '编辑选手' : '添加选手' }}</h3>
        <el-button @click="$emit('update:visible', false)" type="text">×</el-button>
      </div>
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="数字ID" prop="id">
          <el-input v-model="form.id" placeholder="请输入数字ID" />
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入选手昵称" />
        </el-form-item>

        <el-form-item label="擅长位置" prop="positions">
          <el-checkbox-group v-model="form.positions">
            <el-checkbox v-for="position in allPositions" :key="position.value" :label="position.value">
              {{ position.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="段位" prop="rank">
          <el-select v-model="form.rank" placeholder="请选择段位" style="width: 100%">
            <el-option v-for="rank in allRanks" :key="rank.value" :label="rank.label" :value="rank.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="最高天梯分" prop="highestMmr">
          <el-input-number 
            v-model="form.highestMmr" 
            placeholder="请输入最高天梯分" 
            :min="0" 
            :max="20000" 
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="能力值" prop="ability">
          <el-rate 
            v-model="form.ability" 
            :max="6" 
            :texts="['1星', '2星', '3星', '4星', '5星', '6星']"
            show-text
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="词条属性" prop="tags">
          <el-tag
            v-for="(tag, index) in form.tags"
            :key="index"
            closable
            @close="removeTag(index)"
            style="margin-right: 8px; margin-bottom: 8px;"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="inputRef"
            v-model="inputValue"
            class="tag-input"
            size="small"
            @keyup.enter="addTag"
            @blur="addTag"
            style="width: 120px;"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">
            + 添加词条
          </el-button>
        </el-form-item>
      </el-form>

      <div class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { Player } from '@dx-fun-group/shared-types'
import { PlayerPosition, PlayerRank } from '@dx-fun-group/shared-types'
import { createPlayer, updatePlayer } from '../../services/playerService'
import { validateNickname, validatePositions, validateHighestMmr } from '../../utils/playerUtils'

interface Props {
  visible: boolean
  player?: Player | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)
const inputRef = ref<HTMLInputElement>()
const inputVisible = ref(false)
const inputValue = ref('')

const form = ref({
  id: '',
  nickname: '',
  positions: [] as PlayerPosition[],
  rank: '' as PlayerRank | '',
  highestMmr: 0,
  ability: 1,
  tags: [] as string[],
  behaviorScore: 10
})

// 词条管理方法
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const addTag = () => {
  if (inputValue.value && form.value.tags.length < 10) {
    form.value.tags.push(inputValue.value)
    inputValue.value = ''
  }
  inputVisible.value = false
}

const removeTag = (index: number) => {
  form.value.tags.splice(index, 1)
}

const allPositions = [
  { value: PlayerPosition.CARRY, label: '优势路' },
  { value: PlayerPosition.MID, label: '中路' },
  { value: PlayerPosition.OFFLANE, label: '劣势路' },
  { value: PlayerPosition.SUPPORT, label: '辅助' },
  { value: PlayerPosition.HARD_SUPPORT, label: '纯辅助' }
]

const allRanks = [
  { value: PlayerRank.HERALD, label: '先锋' },
  { value: PlayerRank.GUARDIAN, label: '卫士' },
  { value: PlayerRank.CRUSADER, label: '中军' },
  { value: PlayerRank.ARCHON, label: '统帅' },
  { value: PlayerRank.LEGEND, label: '传奇' },
  { value: PlayerRank.ANCIENT, label: '万古流芳' },
  { value: PlayerRank.DIVINE, label: '超凡入圣' },
  { value: PlayerRank.IMMORTAL, label: '冠绝一世' }
]

const isEdit = computed(() => !!props.player)

const rules: FormRules = {
  id: [
    { required: true, message: '请输入数字ID', trigger: 'blur' },
    { pattern: /^\d+$/, message: 'ID必须为数字', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { validator: (_rule, value, callback) => {
      const error = validateNickname(value)
      if (error) {
        callback(new Error(error))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  positions: [
    { required: true, message: '请选择擅长位置', trigger: 'change' },
    { validator: (_rule, value, callback) => {
      const error = validatePositions(value)
      if (error) {
        callback(new Error(error))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
  rank: [
    { required: true, message: '请选择段位', trigger: 'change' }
  ],
  highestMmr: [
    { required: true, message: '请输入最高天梯分', trigger: 'blur' },
    { validator: (_rule, value, callback) => {
      const error = validateHighestMmr(value)
      if (error) {
        callback(new Error(error))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  ability: [
    { required: true, message: '请选择能力值', trigger: 'change' }
  ],
  tags: [
    { type: 'array', required: false, message: '词条属性为可选', trigger: 'change' }
  ]
}

const resetForm = () => {
  form.value = {
    id: '',
    nickname: '',
    positions: [],
    rank: '',
    highestMmr: 0,
    ability: 1,
    tags: [],
    behaviorScore: 10
  }
  formRef.value?.clearValidate()
}

watch(() => props.player, (player) => {
  if (player) {
    form.value = {
      id: player.id,
      nickname: player.nickname,
      positions: [...player.positions],
      rank: player.rank,
      highestMmr: player.highestMmr,
      ability: player.ability,
      tags: [...player.tags],
      behaviorScore: player.behaviorScore ?? 10
    }
  } else {
    resetForm()
  }
}, { immediate: true })

const handleOverlayClick = () => {
  emit('update:visible', false)
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    if (isEdit.value && props.player) {
      const updatedPlayer = await updatePlayer(props.player.id, {
        id: form.value.id,
        nickname: form.value.nickname,
        positions: form.value.positions,
        rank: form.value.rank as PlayerRank,
        highestMmr: form.value.highestMmr,
        ability: form.value.ability,
        tags: form.value.tags,
        behaviorScore: form.value.behaviorScore
      })

      if (updatedPlayer) {
        console.log('更新成功')
        emit('success')
      } else {
        console.error('更新失败')
      }
    } else {
      await createPlayer({
        id: form.value.id,
        nickname: form.value.nickname,
        positions: form.value.positions,
        rank: form.value.rank as PlayerRank,
        highestMmr: form.value.highestMmr,
        ability: form.value.ability,
        tags: form.value.tags,
        behaviorScore: form.value.behaviorScore
      })

      console.log('创建成功')
      emit('success')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  min-width: 500px;
  max-width: 90vw;
  max-height: 90vh;
  overflow-y: auto;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-header h3 {
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}

.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}
</style>
